<template>
  <a-modal
    :visible="props.visible"
    @update:visible="emits('update:visible', false)"
    title="修改密码"
    @ok="handleModifyPassword"
  >
    <a-form ref="formRef" :model="modifyPassword">
      <a-form-item :required="true" name="oldPwd" label="原密码">
        <a-input-password v-model:value="modifyPassword.oldPwd" placeholder="请输入原密码" />
      </a-form-item>
      <a-form-item :required="true" name="newPwd" label="新密码">
        <a-input-password v-model:value="modifyPassword.newPwd" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item :required="true" name="rePwd" label="新密码">
        <a-input-password v-model:value="modifyPassword.rePwd" placeholder="请再次输入新密码" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { ref, reactive } from 'vue'
import { user_updatePassword } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const props = defineProps({
  visible: {
    type: Boolean
  }
})
const emits = defineEmits(['update:visible'])
const formRef = ref()
const modifyPassword = reactive({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})
const handleModifyPassword = async () => {
  try {
    const { newPwd, rePwd, oldPwd } = await formRef.value.validateFields()
    if (newPwd !== rePwd) {
      return message.error('两次密码输入不一致')
    }
    await user_updatePassword({ password: newPwd, oldPwd })
    message.success('密码修改成功，请重新登录')
    emits('update:visible', false)
    setTimeout(() => {
      userStore.logout()
    }, 800)
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}
</script>
